/**
 * 将 Cookie 字符串转换为 JSON 对象
 * @param cookieString
 * @returns {{}}
 */
export function cookieToJson(cookieString) {
    // 处理空字符串
    if (!cookieString || typeof cookieString !== 'string') {
        return {};
    }
    // 分割 Cookie 字符串
    const cookies = cookieString.split(';');
    const result = {};
    // 遍历每个 Cookie
    for (const cookie of cookies) {
        // 跳过空字符串
        if (!cookie.trim()) {
            continue;
        }
        // 查找第一个等号位置
        const equalsIndex = cookie.indexOf('=');

        // 如果没有等号，跳过这个 Cookie
        if (equalsIndex === -1) {
            continue;
        }
        // 提取键和值
        const name = cookie.substring(0, equalsIndex).trim();
        let value = cookie.substring(equalsIndex + 1).trim();
        // 处理可能的 URL 编码
        try {
            value = decodeURIComponent(value);
        } catch (e) {
            // 如果解码失败，使用原始值
            console.warn(`Failed to decode cookie value: ${value}`, e);
        }
        // 添加到结果对象
        result[name] = value;
    }
    return result;
}

/**
 * 根据 Cookie 获取用户名
 * @returns {string | undefined}
 */
export function getUsername() {
    const cookies = cookieToJson(document.cookie);
    return cookies['username'];
}

/**
 * 根据 Cookie 获取用户角色
 * @returns {string | undefined}
 */
export function getRole() {
    const cookies = cookieToJson(document.cookie);
    return cookies['role'];
}

/**
 * 刷新验证码
 * @param img_obj
 */
export function refreshCaptcha(img_obj) {
    img_obj.attr("src", "http://www.woniu-news.com:8082/captcha.php?t=" + Math.random())
}

/**
 * 上传文件，返回图片地址
 * @param file_obj
 * @returns {Promise<string>}
 */
export function uploadFile(file_obj) {
    return new Promise((resolve, reject) => {
        let formData = new FormData()
        let file = file_obj[0].files[0]
        formData.append("file", file)

        $.ajax({
            url: "http://www.woniu-news.com:8082/upload.php",
            type: "POST",
            xhrFields: {withCredentials: true},
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: (resp) => {
                if (resp.code === 200) {
                    alert(resp.message)
                    resolve(resp.url) // ✅ 成功时调用 resolve
                } else {
                    alert(resp.message)
                    reject(resp.message)
                }
            },
            error: (xhr, status, err) => {
                alert(err.message)
                reject(err)
            }
        });
    });
}

/**
 * 从url中获取参数
 * @param key
 * @returns {string | null}
 */
export function getValueFromUrl(key) {
    const url = new URL(window.location.href)
    return url.searchParams.get(key)
}